//
//  MyRecommendFriendController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 16/5/4.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//


#import "MyRecommendFriendController.h"
#import "MembersShareController.h"
#import "MemberAwardController.h"
#import "RulesOrFriendController.h"
//untils
#import "MTA.h"
#import "AppDelegate.h"
#import "RDVTabBarController.h"
#import "Global.h"
#import "UIColor+Hex.h"
#import "ManagerHttpBase.h"
#import "ManagerGlobeUntil.h"
#import "NSString+Conversion.h"
#import "MJRefresh.h"
//view
#import "MyRecommeFriendHeadView.h"
#import "MyRecommeFriendCell.h"
#import "EmptyPageView.h"
//ViewMOdel
#import "MyWalletViewModel.h"
@interface MyRecommendFriendController ()<UITableViewDataSource,UITableViewDelegate,MyRecommeFriendHeadViewDelegate>
@property (nonatomic ,strong)UITableView *tableView;
@property (nonatomic ,strong)MyRecommeFriendHeadView *headView;
@property (nonatomic, strong)MyWalletViewModel *viewModel;
@property (nonatomic) NSInteger currentPage;//分页
@property (nonatomic, strong)NSMutableArray *dataSource;//数据源
@property (nonatomic)NSInteger totalCount;//总条数
@property (nonatomic,strong)EmptyPageView *emptyView;//空视图
@end

@implementation MyRecommendFriendController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title =@"推荐好友";
    [self addBackNavItem];
    [self setSubView];
    self.dataSource =[[NSMutableArray alloc]init];
    self.currentPage = 1;
    self.totalCount = 0;
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        //请求商品详情数据
        [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                                  inView:self.view];
        [_headView setSubViewDataWithFirendNum:[NSString marketLastTwoByteOfStringIsZero:self.recommendFriendNum]];
        //第一次进请求数据
        [self loadProfitDataWithPageNum:self.currentPage PageSize:kRequestLimit SearchType:@"4"];
    }else{
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"网络连接中断~" inView:self.view];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"推荐的好友"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"推荐的好友"];
}

#pragma mark -- requestData
-(void)loadProfitDataWithPageNum:(NSInteger )PageNum PageSize:(NSInteger )PageSize SearchType:(NSString *)SearchType
{
    
    [self.viewModel requestProfitWithPageNum:PageNum PageSize:PageSize SearchType:SearchType success:^(NSArray *successMsg) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:successMsg];
        _totalCount =self.viewModel.totalCount;
        if (self.dataSource.count ==0) {
            _tableView.tableFooterView= _emptyView;
            
        }else{
            UIView *footView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 0.1)];
            _tableView.tableFooterView =footView;
        }
        [_tableView reloadData];
        [self endRefresh];
    } failure:^(NSString *failureMessage) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:failureMessage inView:self.view];
        [self endRefresh];
    }];
    
}

#pragma mark -- MyRecommeFriendHeadViewDelegate
-(void)shareToFriendJump
{
    if ([self.userLevel isEqualToString:@"2"]) {
        MembersShareController  *shareVc = [[MembersShareController alloc]init];
        [self.navigationController pushViewController:shareVc animated:YES];
    }else{
        MemberAwardController  *awardVc = [[MemberAwardController alloc]init];
        [self.navigationController pushViewController:awardVc animated:YES];
    }
}
#pragma mark -- UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    if (self.dataSource.count ==0) {
        return 1;
    }else{
        return self.dataSource.count +1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row ==0) {
        static  NSString *cellIndentifier = @"filterCell2";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIndentifier];
            //            //下划线
            UIButton *backGroundBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            backGroundBtn.frame = CGRectMake(VIEW_WIDTH/3*2, 0, cell.frame.size.width, cell.frame.size.height);
            backGroundBtn.backgroundColor = [UIColor clearColor];
            [cell.contentView addSubview:backGroundBtn];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.textLabel.text = @"推荐的好友";
        cell.textLabel.font = [UIFont systemFontOfSize:FontSize(15)];
        NSMutableAttributedString *detailText = [[NSMutableAttributedString alloc] initWithString:@"如何推荐好友"];
        NSRange detailTextRange = {0, [detailText length]};
        [detailText addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:detailTextRange];
        cell.detailTextLabel.attributedText = detailText;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shareToFriendsClick)];
        [cell.detailTextLabel addGestureRecognizer:tap];
        cell.detailTextLabel .userInteractionEnabled = YES;
        cell.detailTextLabel.font = [UIFont systemFontOfSize:FontSize(14)];
        
        return cell;
        
    }else{
        static NSString *ID = @"MyWalletCell";
        MyRecommeFriendCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
         NSDictionary *dataDic =[self.dataSource objectAtIndex:indexPath.row-1];
        if (!cell) {
            cell = [[MyRecommeFriendCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            cell.backgroundColor =[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell setSubViewWithTimeText:[dataDic objectForKey:@"badyText"] UserName:[dataDic objectForKey:@"titleText"] MoneyText:[dataDic objectForKey:@"moneyText"]];
        return cell;
    }
}
-(void)shareToFriendsClick
{
    RulesOrFriendController *friendVc=[[RulesOrFriendController alloc]init];
    friendVc.rulesOrFriendType=kFriendType;
    [self.navigationController pushViewController:friendVc animated:YES];
}
//黑条效果
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return HightScalar(12);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *views = [[UIView alloc]init];
    views.backgroundColor = [UIColor clearColor];
    return views;
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return HightScalar(50);
    }else{
    return HightScalar(67);
    }
}
#pragma mark - 上拉/下拉  更新数据
-(void)headerRereshing {
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        self.currentPage = 1;
        [self loadProfitDataWithPageNum:self.currentPage PageSize:kRequestLimit SearchType:@"4"];
    }else{
        [self endRefresh];
    }
    
}

-(void)footerRereshing
{
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        if (self.currentPage*kRequestLimit < self.totalCount) {
            self.currentPage++;
            [self loadProfitDataWithPageNum:self.currentPage PageSize:kRequestLimit SearchType:@"4"];
        } else {
            [_tableView setFooterRefreshingText:@"已加载完全部数据~"];
            [self endRefresh];
        }
    }else{
        [self endRefresh];
    }
}
- (void)endRefresh
{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
}

#pragma mark -- MyWalletCellDelegate
-(void)setSubView
{
    _tableView =[[UITableView  alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT -64) style:UITableViewStyleGrouped];
    _tableView.backgroundColor =[UIColor colorWithHexString:@"#efefef"];
    _tableView.delegate =self;
    _tableView.dataSource =self;
    //添加下拉刷新
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //添加上拉加载更多
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    _headView =[[MyRecommeFriendHeadView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, HightScalar(125))];
    _headView.delegate = self;
    _tableView.tableHeaderView =_headView;
    _emptyView =[[EmptyPageView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT-HightScalar(175)-64) EmptyPageViewType:kRecommendFriendView];
    _emptyView.backgroundColor=[UIColor colorWithHexString:@"#efefef"];
    _tableView.tableFooterView = _emptyView;
    [self.view addSubview:_tableView];
    
}
- (MyWalletViewModel*)viewModel {
    if (!_viewModel) {
        _viewModel = [[MyWalletViewModel alloc]init];
    }
    return _viewModel;
}
-(void)backBtnAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

